# -*- coding: utf-8 -*-
import bs4,requests,lxml,json,re
from multiprocessing import Pool
erp_update = 'http://erp-update.fdccloud.com'
erpapi = 'http://erpapi.fdccloud.com/index/index'

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Content-Type':'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
}

LoginHeaders = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
}
#设置代理，用户fiddler抓取
proxies = {
        # "http": "127.0.0.1:8888"
    }
#初始化session，后续请求就能自动带上cookies
sess = requests.session()
sess_erpservice = requests.session()

def tags_val(tag, key='', index=0):
    '''
    return html tag list attribute @key @index
    if @key is empty, return tag content
    '''
    if len(tag) == 0 or len(tag) <= index:
        return ''
    elif key:
        txt = tag[index].get(key)
        return txt.strip(' \t\r\n') if txt else ''
    else:
        txt = tag[index].text
        return txt.strip(' \t\r\n') if txt else ''


def tag_val(tag, key=''):
    '''
    return html tag attribute @key
    if @key is empty, return tag content
    '''
    if tag is None:
        return ''
    elif key:
        txt = tag.get(key)
        return txt.strip(' \t\r\n') if txt else ''
    else:
        txt = tag.text
        return txt.strip(' \t\r\n') if txt else ''

#登录
def login():
    # data= 'userId=wf'+user+'&userPassword='+passwd
    data = {
        'userId':'wf',
        'userPassword':'wf1qaz'
    }
    resp = sess.post(
        url=erp_update + '/home/login/ajax-login',
        headers=LoginHeaders, data=data,proxies=proxies)
    dict_resp= json.loads(resp.content)
    if dict_resp['isSuccess'] =='1':
        pass
    else:
        print ('登录失败')

#查询客户guid
def GetCustomerGUID(CustName):
    resp = sess.get(
        url=erp_update + '/v2/package-manager/cust-prod-install-summary?search_key=' + CustName + '&status=0&prod_key=all',
        headers=headers,proxies=proxies)
    # print resp.content
    soup = bs4.BeautifulSoup(resp.text,'lxml')
    tags = soup.select('tbody.cust-list-body tr')
    custInfos = soup.select('tbody.cust-list-body tr td')
    custs = []
    for i,item in enumerate(custInfos):
        if ((i+1)%6) != 0 :
            custs.append(tag_val(item))
    # print (json.dumps(custs,encoding='UTF-8', ensure_ascii=False))
    print (custs)
    # print custs
    guids = []
    for item in tags:
        guid = tag_val(item,'_cstguid')
        guids.append(guid)
    print (guids)
    return guids

#通过客户guid获取erpservice地址
def GetCustomerApiUrl(Guid):
    resp = sess.get(
        url=erp_update+'/v2/package-manager/add-customer?is_edit=1&cst_guid='+Guid,
        headers = headers, proxies = proxies)
    soup = bs4.BeautifulSoup(resp.text, 'lxml')
    tags = soup.select('[name="api_site"]')
    erpservice_url=tags_val(tags,'value')
    print (erpservice_url)
    return erpservice_url

#通过erpservice获取信息TargetUrl，用于拼接链接登陆自更新服务
def GetTargetUrlByErpService(erpservice):
    resp = requests.get(url=erpservice,
        headers = headers, proxies = proxies)
    soup = bs4.BeautifulSoup(resp.text, 'lxml')
    tags = soup.select('div h3')
    custs = []
    for i, item in enumerate(tags):
        if i != 0:
            custs.append(tag_val(item))
    # print (json.dumps(custs,encoding='UTF-8', ensure_ascii=False))
    print (custs)

    IP = re.findall(u"：(.+)",custs[1])[0]
    # print IP
    return IP


#登陆erpservice
def Login_ERPService(erpservice,IP):
    data = {
        'name':'admin',
        'pwd':'1'
    }
    # erpservice_loin = 'http://erp.xinlizd.com:8870/erpservice/AutoUpgrade.ashx?x-target-url=http://172.168.1.21:50777/api/user/login.aspx?'
    resp = sess_erpservice.post(url=erpservice+'/AutoUpgrade.ashx?x-target-url=http://'+IP+':50777/api/user/login.aspx?',
                        headers=LoginHeaders, data=data,proxies=proxies)
    if resp.text =='ok':
        pass
    else:
        print (erpservice+'登录失败')

#获取客户站点配置信息，主要是站点服务器ip
def GetSiteConfigInfo(erpservice,IP,includeDispatchService):
    '''

    :param IP: 协调服务ip
    :param includeDispatchService: includeDispatchService=false查询站点配置信息，=true查询服务监控站点
    :return:
    '''
    #includeDispatchService=false查询站点配置信息，=true查询服务监控站点
    data = {
        'onlyConnectedHost': 'false'
    }
    resp = sess_erpservice.post(
        url=erpservice + '/AutoUpgrade.ashx?x-target-url=http://' + IP + ':50777/api/upgrade/get_register_servers.aspx?includeDispatchService='+includeDispatchService+'&=undefined',
        headers=LoginHeaders, data=data, proxies=proxies)
    try:
        content_dict = json.loads(resp.content)
        data_list = content_dict['data']
        AddrIP = []
        ServerRoles = []
        if includeDispatchService.lower() == 'false':
            for Addr in data_list:
                AddrIP.append(Addr['IP'])
            print (AddrIP)
            # return AddrIP
        else:
            for Addr in data_list:
                AddrIP.append(Addr['IP'])
                #将列表roles列表转换为字符串
                str_role =",".join(str(i) for i in Addr['ServerRoles'])
                ServerRoles.append(str_role)
                # print AddrIP,ServerRoles
        ip_roles = dict(zip(AddrIP,ServerRoles ))
        print (ip_roles)
        return ip_roles
    except:
        print ("无站点信息")
        raise

#获取服务器站点详情
def GetSiteConfigDetails(erpservice,ServerIP,site):
    data = {
        'ip': site
    }
    resp = sess_erpservice.post(
        url=erpservice + '/AutoUpgrade.ashx?x-target-url=http://' + ServerIP + ':50777/api/upgrade/get_products_in_server.aspx?=undefined',
        headers=LoginHeaders, data=data, proxies=proxies)
    try:
        content_dict = json.loads(resp.content)
        data_list = content_dict['data']['products']
        result = {'1_siteIP':site}
        for i in data_list:
            if '工作' in i['product_name']:
                site_name = i['site_name']
                product_name=i['product_name']
                result[site_name]=product_name
        print (sorted(result.items()))
        # print (json.dumps(sorted(result.items()), encoding='UTF-8', ensure_ascii=False))
    except:
        print ("无站点信息")
        raise

#获取服务器监控问题
def GetServiceMonitor(erpservice,ServerIP,site,roles):
    """
    :param erpservice: 接口地址
    :param ServerIP: 协调服务地址
    :param site: 站点地址，包含协调服务站点
    :param roles: 站点类型，更新服务0，协调服务1
    :return:
    """
    data = {
        'ip': site,
        'roles':roles
    }
    resp = sess_erpservice.post(
        url=erpservice + '/AutoUpgrade.ashx?x-target-url=http://' + ServerIP + ':50777/api/upgrade/get_service_monitor_infos.aspx?=undefined',
        headers=LoginHeaders, data=data, proxies=proxies)
    try:
        content_dict = json.loads(resp.content)
        data_list = content_dict['data']
        result={}
        for i in data_list:
            service_des = i['service_des']
            service_status=i['service_status']
            if service_status != 0:
                result[service_des]=service_status
                result['site'] = site
        if result:
            # print (json.dumps(result, encoding='UTF-8', ensure_ascii=False))
            print (result)
        else:
            print (site+"服务正常")
    except:
        print ("无站点信息")

#传入客户列表，查询自更新服务情况
def ExecuteQuery(customerLIst):
    """
    传入客户列表，查询自更新服务情况
    :param customerLIst:
    :return:
    """
    for customer in customerLIst:
        print ("===========================================================================================")
        login()
        #输入客户名称
        guids = GetCustomerGUID(customer)
        erpservices = []
        for guid in guids:
            erpservices.append(GetCustomerApiUrl(guid))
        for erpservice in erpservices:
            try:
                ServiceIP=GetTargetUrlByErpService(erpservice)
                Login_ERPService(erpservice,ServiceIP)

                AddrIP:dict = GetSiteConfigInfo(erpservice,ServiceIP,'true')
                p = Pool(8)
                p1 = Pool(8)
                # for Site,role in AddrIP.iteritems():
                for Site,role in AddrIP.items():
                    p.apply_async(GetServiceMonitor,args=(erpservice,ServiceIP,Site,role,))
                    #如果服务器只有协调服务，不查询站点配置页
                    if role != '1':
                        p1.apply_async(GetSiteConfigDetails, args=(erpservice,ServiceIP,Site))
                    #     GetSiteConfigDetails(erpservice,ServiceIP,Site)
                    # GetServiceMonitor(erpservice,ServiceIP,Site,role)
                p.close()
                p.join()
                p1.close()
                p1.join()
            except:
                print("客户更新服务异常。。。")
                raise

#---------------------------------------开始查询------------------------------------------
if __name__=='__main__':
    custList=['河南常绿集团置业有限公司']
    ExecuteQuery(custList)
